import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'

import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import pxToViewport from 'postcss-px-to-viewport'
import unpluginAutoImport from 'unplugin-auto-import/vite'
import unpluginVueComponents from 'unplugin-vue-components/vite'
import { VantResolver } from 'unplugin-vue-components/resolvers'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'

// https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/import.meta
const pathResolve = dir => fileURLToPath(new URL(dir, import.meta.url))

// https://vitejs.dev/config/
export default defineConfig({
  base: './',
  resolve: {
    alias: {
      '@': pathResolve('./src'),
    },
  },
  css: {
    /**
     * css modules 设置
     * @see https://cn.vitejs.dev/guide/features.html#css-modules
     */
    modules: {
      localsConvention: 'camelCase',
    },
    postcss: {
      plugins: [pxToViewport({ viewportWidth: 375 })],
    },
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
      },
    },
  },
  plugins: [
    vue(),
    vueJsx(),
    // 自动按需引入js https://github.com/antfu/unplugin-auto-import
    unpluginAutoImport({
      imports: [
        'vue',
        'vue-router',
        {
          vant: [
            'showToast',
            'showSuccessToast',
            'showFailToast',
            'closeToast',
            'showLoadingToast',
            'showDialog',
            'showNotify',
            'showImagePreview',
          ],
          '@/helpers/auto-import': ['dayjs', 'elog', '_'],
        },
      ],
      eslintrc: {
        enabled: true,
        filepath: pathResolve('./.eslintrc-auto-import.json'),
        globalsPropValue: 'readonly',
      },
      dts: './@types/vite-auto-import.d.ts',
    }),
    // 自动按需引入插件 https://github.com/antfu/unplugin-vue-components
    unpluginVueComponents({
      // 自动按需引入 如下目录内的vue组件
      dirs: ['src/components'],
      resolvers: [
        VantResolver(),
        AntDesignVueResolver({
          importStyle: 'less',
          resolveIcons: true,
        }),
      ],
      dts: './@types/vite-components.d.ts',
    }),
  ],
})
